<template>
  <div class="wraterfall-wrap" :style="wrapStyle">
    <template v-if="col > 1">
      <div
        v-for="(i, index) in col"
        :key="i"
        :ref="`col${index}`"
        :style="itemStyle"
        class="waterfall-item">
        <div v-for="(item, $index) in renderList[index]" :key="$index">
          <slot name="content" :data="item"></slot>
        </div>
      </div>
    </template>
    <template v-else>
      <div v-for="(item, index) in list" :key="index" ref="col0">
        <slot name="content" :data="item"></slot>
      </div>
    </template>
  </div>
</template>

<script>
/**
 * @file waterfall
 */
export default {
  name: 'WaterFall',
  props: {
    list: {
      type: Array,
      default: () => []
    },
    // container height
    height: {
      type: Number,
      default: 500
    },
    col: {
      type: Number,
      default: 2
    },
    itemWidth: {
      type: Number,
      default: 100
    },
    itemSpacing: {
      type: Number,
      default: 20
    }
  },
  computed: {
    wrapStyle() {
      return {
        height: this.height + 'px'
      }
    },
    itemStyle() {
      return {
        width: this.itemWidth + 'px',
        'margin-right': this.itemSpacing + 'px'
      }
    }
  },
  data() {
    return {
      renderList: []
    }
  },
  mounted() {
    // 多列时，初始化
    if (this.col > 1) {
      this.initData()
      this.initLayout(0)
    }
  },
  methods: {
    initData() {
      for(let i = 0; i < this.col; i++) {
        this.renderList[i] = []
      }
    },
    initLayout(index) {
      if (index >= this.list.length) {
        return
      }
      const colHeightList = []
      for (let i = 0; i < this.col; i++) {
        colHeightList[i] = this.$refs[`col${i}`][0].offsetHeight
      }
      const min = colHeightList.indexOf(Math.min.apply(Math, colHeightList))
      const target = this.renderList[min].concat(this.list[index])
      this.$set(this.renderList, min, target)
      this.$nextTick(() => {
        this.initLayout(++index)
      })
    }
  }
}
</script>

<style lang="less" scoped>
.waterfall-wrap {
  overflow-y: auto;
  width: 100%;

  .waterfall-item {
    float: left;
  }
}
</style>
